<?php
/**
 * @param $status - 0:失败,1成功
 * @param $content - $codeMap错误代码或正确时的返回值
 * @param $msg 自定义错误代码
 */
function ajax_feedback($status, $content=null, $msg=null){
    $codeMap = array(
        '1001'=>'未知/未捕获的异常',
        '1002'=>'数据库连接错误',
        '1003'=>'服务器错误', 
    
        '1101'=>'请填写完整的注册信息',
        '1102'=>'用户名已被注册，更换一个吧',
        '1103'=>'用户名只能是纯字母',
        '1104'=>'密码长度不够',
    
        '1111'=>'请填写用户名密码',
        '1112'=>'用户名或密码不正确',
        '1113'=>'用户已关闭',
        '1114'=>'原密码填写不正确',
        
        '1201'=>'请填写关键词',
        '1202'=>'请填写回复内容',
    
        '1301'=>'请上传文件',
        '1302'=>'无效的文件扩展名',
        '1303'=>'上传的文件太大',
        '1304'=>'上传失败',
			
        '1306'=>'请选择类别',
        '1307'=>'请填写音乐名称',
        '1308'=>'请填写链接地址',
        '1309'=>'请填写视频名',
		
        '1310'=>'请填写位置名称',
        '1311'=>'请填写维度',
        '1312'=>'请填写经度',
        '1313'=> $msg,
		
		
    );
    
    $detail = array('success'=>$status);

    if(!$msg && !is_array($content) && isset($codeMap[$content])) $msg = $codeMap[$content];
    if($status==0) $detail['errorno'] = $content; else $detail['data'] = $content;
    if($msg) $detail['msg'] = $msg;
    exit(json_encode($detail));
}
//是否ajax请求
function isXmlHttpRequest() {
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
}
//url请求方法：POST|GET
function method_is($method){
    $method = strtoupper($method);
	return $_SERVER['REQUEST_METHOD']==$method ? true : false;
}
//测试
function test_auth(){
	$user=$_SERVER['PHP_AUTH_USER'];
	$pass=$_SERVER['PHP_AUTH_PW'];
	if($user !='wgt' || $pass !='1qazxsw2'){
		Header("WWW-Authenticate: Basic realm='USER LOGIN'");
		Header("HTTP/1.0 401 Unauthorized");
		exit;
	}
}

//将自动加载model类
if(!function_exists('classAutoLoader')){
	function classAutoLoader($class){
		$classFile=ROOT_PATH.'package/'.str_replace('_','/',strtolower($class)).'.php';
		if(is_file($classFile)&&!class_exists($class)) include $classFile;
	}
}
spl_autoload_register('classAutoLoader');

//权限读取
function level_check($level_content, $check_content) {
    if (!strstr($level_content, $check_content)) {
        header('Content-type: text/html; charset=utf-8');
        echo "<script language='javascript'>";
        echo "	alert ('您没有相关权限！');";
        echo "	window.top.location.href='login.php';";
        echo "</script>";
        die();
    }
}

//函数js_alert弹出信息框并返回到指定页
function js_alert($msg, $go_to) {
    header('Content-type: text/html; charset=utf-8');
    echo "<script language='javascript'>\n";
    if ($msg) {
        echo "alert('$msg');\n";
    }
    if (is_numeric($go_to)) {
        echo 'window.history.go(' . $go_to . ')';
    } else {
        if ($go_to)
            echo "window.location.href='$go_to';\n";
    }
    echo "</script>\n";
    exit();
}

function random($leng) { // 取固定长度的随机数
    $text = '';
    $var  = md5('0123456789');
    $max  = strlen($var) - 1;
    mt_srand((double) microtime() * 1000000);
    for ($i = 0; $i < $leng; $i++) {
        $text .= $var[mt_rand(0, $max)];
    }
    return $text;
}

//utf8编码字符串截取函数
function cut_str($string, $sublen, $start = 0, $code = 'UTF-8') {
    if ($code == 'UTF-8') {
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);

        if (count($t_string[0]) - $start > $sublen)
            return join('', array_slice($t_string[0], $start, $sublen)) . "...";
        return join('', array_slice($t_string[0], $start, $sublen));
    }
    else {
        $start  = $start * 2;
        $sublen = $sublen * 2;
        $strlen = strlen($string);
        $tmpstr = '';
        for ($i = 0; $i < $strlen; $i++) {
            if ($i >= $start && $i < ($start + $sublen)) {
                if (ord(substr($string, $i, 1)) > 129)
                    $tmpstr.= substr($string, $i, 2);
                else
                    $tmpstr.= substr($string, $i, 1);
            }
            if (ord(substr($string, $i, 1)) > 129)
                $i++;
        }
        if (strlen($tmpstr) < $strlen)
            $tmpstr.= "...";
        return $tmpstr;
    }
}

function GetIP() {
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
        $ip = getenv("REMOTE_ADDR");
    else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else
        $ip = "unknown";
    return($ip);
}

//字符串入库前处理
function str_inmysql($str, $nohtml = '', $can_special = '') {
    if ($nohtml == '1') {
        $str = htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
    } else {
        $old_array = array('alert', '<script', 'onclick', 'javascript', 'onload', 'onerror',  '<meta', '<input', '<textarea', 'onmouse');
        $new_array = array('&#097;lert', '&#60;script', '&#111;nclick', '&#106;avascript', '&#111;nload', '&#111;nerror',  '&#60;meta', '&#60;input', '&#60;textarea', '&#111;nmouse');
        if ($can_special != '1') {
            $str = str_ireplace($old_array, $new_array, $str);
        }
        $str = mysql_real_escape_string($str);
    }
    return $str;
}

//得到主域名
function get_mainurl($web_url) {
    $webdomain_array = array('.com.cn', '.edu.cn', '.net.cn', '.gov.cn', '.org.cn', '.mobi', '.info', '.name', '.com', '.net', '.edu', '.org', '.biz', '.cn', '.cc', '.tv', '.us', '.hk', '.tw', '.la', '.in');
    $domain_num      = count($webdomain_array);
    $domainlen_array = array('-7', '-5', '-4', '-3');
    $len_num         = count($domainlen_array);
    $thisdomain      = '';
    for ($i = 0; $i < $len_num; $i++) {
        $back_str = substr($web_url, $domainlen_array[$i]);
        for ($j = 0; $j < $domain_num; $j++) {
            if ($back_str == $webdomain_array[$j]) {
                $thisdomain  = $back_str;
                $have_result = 1;
                break;
            }
        }
        if ($have_result == '1') {
            break;
        }
    }
    if ($have_result == '1') {
        $front_str    = str_replace($thisdomain, '', $web_url);
        $domain       = explode(".", $front_str);
        $name         = array_reverse($domain);
        $front_domain = $name[0];
        if ($front_domain == $front_str) {
            $domain       = explode("/", $front_str);
            $name         = array_reverse($domain);
            $front_domain = $name[0];
        }
        return $front_domain . $thisdomain;
    } else {
        return $web_url;
    }
}

function file_write($filename, $content) {
    if ($file_name = fopen($filename, "w")) {
        flock($file_name, LOCK_EX);
        $file_content = fwrite($file_name, $content);
        fclose($file_name);
        return 1;
    } else {
        return 0;
    }
}

//返回当前IP的城市字符串
function convertip($ip) {
//IP数据文件路径
    $dat_path = 'QQWry.Dat';

//检查IP地址
    if (!preg_match("/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1
\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/", $ip)) {
        return 'IP Address Error';
    }
//打开IP数据文件
    if (!$fd = @fopen($dat_path, 'rb')) {
        return 'IP date file not exists or access denied';
    }

//分解IP进行运算，得出整形数
    $ip    = explode('.', $ip);
    $ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];

//获取IP数据索引开始和结束位置
    $DataBegin = fread($fd, 4);
    $DataEnd   = fread($fd, 4);
    $ipbegin   = implode('', unpack('L', $DataBegin));
    if ($ipbegin < 0)
        $ipbegin += pow(2, 32);
    $ipend     = implode('', unpack('L', $DataEnd));
    if ($ipend < 0)
        $ipend += pow(2, 32);
    $ipAllNum  = ($ipend - $ipbegin) / 7 + 1;

    $BeginNum = 0;
    $EndNum   = $ipAllNum;

//使用二分查找法从索引记录中搜索匹配的IP记录
    while ($ip1num > $ipNum || $ip2num < $ipNum) {
        $Middle = intval(($EndNum + $BeginNum) / 2);

//偏移指针到索引位置读取4个字节
        fseek($fd, $ipbegin + 7 * $Middle);
        $ipData1 = fread($fd, 4);
        if (strlen($ipData1) < 4) {
            fclose($fd);
            return 'System Error';
        }
//提取出来的数据转换成长整形，如果数据是负数则加上2的32次幂
        $ip1num = implode('', unpack('L', $ipData1));
        if ($ip1num < 0)
            $ip1num += pow(2, 32);

//提取的长整型数大于我们IP地址则修改结束位置进行下一次循环
        if ($ip1num > $ipNum) {
            $EndNum = $Middle;
            continue;
        }

//取完上一个索引后取下一个索引
        $DataSeek = fread($fd, 3);
        if (strlen($DataSeek) < 3) {
            fclose($fd);
            return 'System Error';
        }
        $DataSeek = implode('', unpack('L', $DataSeek . chr(0)));
        fseek($fd, $DataSeek);
        $ipData2  = fread($fd, 4);
        if (strlen($ipData2) < 4) {
            fclose($fd);
            return 'System Error';
        }
        $ip2num = implode('', unpack('L', $ipData2));
        if ($ip2num < 0)
            $ip2num += pow(2, 32);

//没找到提示未知
        if ($ip2num < $ipNum) {
            if ($Middle == $BeginNum) {
                fclose($fd);
                return 'Unknown';
            }
            $BeginNum = $Middle;
        }
    }

    $ipFlag = fread($fd, 1);
    if ($ipFlag == chr(1)) {
        $ipSeek = fread($fd, 3);
        if (strlen($ipSeek) < 3) {
            fclose($fd);
            return 'System Error';
        }
        $ipSeek = implode('', unpack('L', $ipSeek . chr(0)));
        fseek($fd, $ipSeek);
        $ipFlag = fread($fd, 1);
    }

    if ($ipFlag == chr(2)) {
        $AddrSeek = fread($fd, 3);
        if (strlen($AddrSeek) < 3) {
            fclose($fd);
            return 'System Error';
        }
        $ipFlag = fread($fd, 1);
        if ($ipFlag == chr(2)) {
            $AddrSeek2 = fread($fd, 3);
            if (strlen($AddrSeek2) < 3) {
                fclose($fd);
                return 'System Error';
            }
            $AddrSeek2 = implode('', unpack('L', $AddrSeek2 . chr(0)));
            fseek($fd, $AddrSeek2);
        } else {
            fseek($fd, -1, SEEK_CUR);
        }

        while (($char = fread($fd, 1)) != chr(0))
            $ipAddr2 .= $char;

        $AddrSeek = implode('', unpack('L', $AddrSeek . chr(0)));
        fseek($fd, $AddrSeek);

        while (($char = fread($fd, 1)) != chr(0))
            $ipAddr1 .= $char;
    } else {
        fseek($fd, -1, SEEK_CUR);
        while (($char = fread($fd, 1)) != chr(0))
            $ipAddr1 .= $char;

        $ipFlag = fread($fd, 1);
        if ($ipFlag == chr(2)) {
            $AddrSeek2 = fread($fd, 3);
            if (strlen($AddrSeek2) < 3) {
                fclose($fd);
                return 'System Error';
            }
            $AddrSeek2 = implode('', unpack('L', $AddrSeek2 . chr(0)));
            fseek($fd, $AddrSeek2);
        } else {
            fseek($fd, -1, SEEK_CUR);
        }
        while (($char = fread($fd, 1)) != chr(0)) {
            $ipAddr2 .= $char;
        }
    }
    fclose($fd);

//最后做相应的替换操作后返回结果
    if (preg_match('/http/i', $ipAddr2)) {
        $ipAddr2 = '';
    }
    $ipaddr = "$ipAddr1 $ipAddr2";
    $ipaddr = preg_replace('/CZ88.Net/is', '', $ipaddr);
    $ipaddr = preg_replace('/^s*/is', '', $ipaddr);
    $ipaddr = preg_replace('/s*$/is', '', $ipaddr);
    if (preg_match('/http/i', $ipaddr) || $ipaddr == '') {
        $ipaddr = 'Unknown';
    }

    return $ipaddr;
}
/*
 自定义获取函数 $_POST[]
*/
function common_po($obj)
{
	$myi = 0;$tmp = ''; $value = '';
	$str='select,delete,update,create,drop,insert,iframe';
	$arr=explode(',',$str);
	$tmp = isset($_POST[$obj]) ? $_POST[$obj] : null;
	$tmp=str_replace("'",'',$tmp);
	$tmp=str_replace('<','&lt;',$tmp);
	$tmp=str_replace('>','&gt;',$tmp);

	if (isset ( $tmp )) {
		if (strtolower(gettype ( $tmp )) != 'array') {
			$val = strtolower ( $tmp );
			if (in_array($val,$arr)) {
				$msg = "获取参数错误，请检查您所提交的数据！以下为不能被提交的数据：\n\n$tmp .";
				echo '<script>top.location.href="/Error.php?msg=' . urlencode ( $msg ) . '";</script>';
			}
			$value = $tmp;
		} else {
			$value = $tmp;
		}
	} else {
		$value = $tmp;
	}
	return $value;
}
/*
 自定义获取函数 $_POST[] 与 $_GET[]
*/
function common_pg($obj)
{
	$tmp = "";$tmp2 = "";
	$returnvalue = "";
	$str="select,delete,update,create,drop,and";
	$arr=explode(',',$str);
	if(isset($_GET[$obj]))
	{
		$tmp =$_GET[$obj];
	}
	else
	{
		$tmp = isset($_POST[$obj]) ? $_POST[$obj] : null;
	}
	////////////////
	if (strtolower(gettype ( $tmp )) != 'array') {
		$tmp2=strtolower($tmp);
	}
	//////////////////
	$tmp2=str_replace("'",'',$tmp2);
	if (in_array($tmp2,$arr)) {
		$msg = "获取参数错误，请检查您所提交的数据！以下为不能被提交的数据：\n\n$tmp .";
		echo '<script>top.location.href="/Error.php?msg=' . urlencode ( $msg ) . '";</script>';
	} else {
		$returnvalue = $tmp;
	}
	return $returnvalue;
}


//某月有多少天
function getMonthLastDay($month, $year) {
    switch ($month) {
        case 4 :
        case 6 :
        case 9 :
        case 11 :
            $days = 30;
            break;
        case 2 :
            if ($year % 4 == 0) {
                if ($year % 100 == 0) {
                    $days = $year % 400 == 0 ? 29 : 28;
                } else {
                    $days = 29;
                }
            } else {
                $days = 28;
            }
            break;

        default :
            $days = 31;
            break;
    }
    return $days;
}

//加密解密码
function passport_encrypt($txt, $key) {
    $txt         = 'cc_' . $txt;
    srand((double) microtime() * 1000000);
    $encrypt_key = md5(rand(0, 48000));
    $ctr         = 0;
    $tmp         = '';
    for ($i = 0; $i < strlen($txt); $i++) {
        $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
        $tmp .= $encrypt_key[$ctr] . ($txt[$i] ^ $encrypt_key[$ctr++]);
    }
    return base64_encode(passport_key($tmp, $key));
}

function passport_decrypt($txt, $key) {
    $txt = passport_key(base64_decode($txt), $key);
    $tmp = '';
    for ($i = 0; $i < strlen($txt); $i++) {
        $md5 = $txt[$i];
        $tmp .= $txt[++$i] ^ $md5;
    }
    $tmp = str_replace('cc_', '', $tmp);
    return $tmp;
}

function passport_key($txt, $encrypt_key) {
    $encrypt_key = md5($encrypt_key);
    $ctr         = 0;
    $tmp         = '';
    for ($i = 0; $i < strlen($txt); $i++) {
        $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
        $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
    }
    return $tmp;
}

//发邮件通知
function send_mail($mail_title, $mail_content, $mailto) {
    global $config_mailstmp;
    global $db_obj;
    include_once("phpmailer/class.phpmailer.php");
    include_once("phpmailer/class.smtp.php");
    $mail              = new PHPMailer();
    $mail->CharSet     = "UTF-8";
    $mail->IsSMTP();
    $mail->Host        = $config_mailstmp['host'];
    $mail->SMTPAuth    = true;
    $mail->Username    = $config_mailstmp['email'];
    $mail->Password    = $config_mailstmp['pass'];
    $mail->Port        = 25;
    $mail->Encoding    = "base64";
    $mail->From        = $config_mailstmp['from'];
    $mail->FromName    = "微库";
    $mail->Subject     = $mail_title;
    $mail->Body        = nl2br($mail_content);
    $mail->AddAddress($mailto);
    $mail->ContentType = "text/html";
    if (!$mail->Send()) {
        $mail_result = $thismail . " 失败" . $mail->ErrorInfo;
        return "Error: " . $mail->ErrorInfo;
    } else {
        return 'success';
    }
    $mail->ClearAddresses();
    $mail->ClearAttachments();
    $mail->SMTPClose();
    $mail = NULL;
}

//格式化日期 2011-03-02 18:22:34或unix时间戳 转换为：3月2日 18:22
function fmt_date($date, $time_flg = TRUE) {
    if (strstr($date, '-')) {
        $date = date("Y-m-d H:i:s", strtotime($date));
    } else {
        $date = date("Y-m-d H:i:s", $date);
    }
    $date        = substr($date, 5, 11);
    $date_array1 = explode('-', $date);
    $month       = (int) $date_array1[0];
    $date_array2 = explode(' ', $date_array1[1]);
    $day         = (int) $date_array2[0];
    $otherdate   = $date_array2[1];
    if ($time_flg) {
        return $month . '月' . $day . '日 ' . $otherdate;
    } else {
        return $month . '月' . $day . '日 ';
    }
}

//app加密
function app_url_encode($param) {
    return base64_encode($param);
}

//app解密
function app_url_decode($param) {
    if (empty($param)) {
        return FALSE;
    }
    $base64_data = base64_decode($param);
    $array       = explode('&', $base64_data);
    foreach ($array as $value) {
        $temp             = explode('=', $value);
        $data[$temp['0']] = $temp['1'];
    }
    return $data;
}

//去除html标签
function deletehtml($str) {
    $str = trim($str);
    $str = strip_tags($str, "");
    $str = str_replace("\t", "", $str);
    $str = str_replace("\r\n", "", $str);
    $str = str_replace("\r", "", $str);
    $str = str_replace("\n", "", $str);
    $str = str_replace(" ", " ", $str);
	$str = str_replace("&nbsp;", " ", $str);
    return trim($str);
}

//按二维数组某键值排序
function multi_array_sort($multi_array, $sort_key, $sort = SORT_ASC) {
    if (is_array($multi_array)) {
        foreach ($multi_array as $row_array) {
            if (is_array($row_array)) {
                $key_array[] = $row_array[$sort_key];
            } else {
                return false;
            }
        }
    } else {
        return false;
    }
    array_multisort($key_array, $sort, $multi_array);
    return $multi_array;
}

//随机函数
function code_random($length = 6 , $numeric = 0) {
	PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
	if($numeric) {
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}

//curl
function curl_request($url,$data = null){
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	if (!empty($data)){
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	}
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	$output = curl_exec($curl);
	curl_close($curl);
	return $output;
}

//判断是否从微信中打开的
function is_inweixin() {
    if (!strstr($_SERVER["HTTP_USER_AGENT"], 'MicroMessenger') && $_SERVER["HTTP_X_REQUESTED_WITH"] == 'im.yixin') {
        die("<script type='text/javascript'>请在微信浏览器中打开！</script>");
    }
}

//获取登录session
function get_suser($key='suser'){
    return $_SESSION[$key];
}
//设置session
function set_suser($data,$key='suser'){
	$_SESSION[$key] = $data;
}   
//判断是否登录
function check_login(){
    $suserSession=get_suser();
	if(empty($suserSession['name'])){
		echo '<script type="text/javascript">
				if(window.top==window.self){
					window.location.href="../../../index.php?m=Admin&c=index&a=login";
				}else{
					parent.window.location.reload();
				}
			  </script>';
		die();
	}
}

//实例化类
function D($table){
	return new Model_Subtable($table);
}

/**
 * 删除空格和中括号
 * @param unknown $str
 */
function trimall($str)//删除空格
{
	$qian=array(" ","　","\t","\n","\r","\s","[","]");
	$hou=array("","","","","","","","");
	return str_replace($qian,$hou,$str);
}

/**
 * 汉字转拼音
 */
function Pinyin($_String, $_Code='gb2312'){

	$_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha".

			"|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|".

			"cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er".

			"|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui".

			"|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang".

			"|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang".

			"|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue".

			"|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne".

			"|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen".

			"|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang".

			"|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|".

			"she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|".

			"tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu".

			"|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you".

			"|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|".

			"zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";

	$_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990".

			"|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725".

			"|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263".

			"|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003".

			"|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697".

			"|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211".

			"|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922".

			"|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468".

			"|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664".

			"|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407".

			"|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959".

			"|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652".

			"|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369".

			"|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128".

			"|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914".

			"|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645".

			"|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149".

			"|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087".

			"|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658".

			"|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340".

			"|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888".

			"|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585".

			"|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847".

			"|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055".

			"|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780".

			"|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274".

			"|-10270|-10262|-10260|-10256|-10254";

	$_TDataKey   = explode('|', $_DataKey);

	$_TDataValue = explode('|', $_DataValue);

	$_Data = array_combine($_TDataKey,  $_TDataValue);

	arsort($_Data);

	reset($_Data);

	if($_Code!= 'gb2312') $_String =_U2_Utf8_Gb($_String);

	$_Res = '';

	for($i=0; $i<strlen($_String); $i++){

		$_P = ord(substr($_String, $i, 1));

		if($_P>160){

			$_Q = ord(substr($_String, ++$i, 1)); $_P = $_P*256 + $_Q - 65536;

		}

		$_Res .= _Pinyin($_P, $_Data);

	}

	return preg_replace("/[^a-z0-9]*/", '', $_Res); //???????

}

function _Pinyin($_Num, $_Data){

	if($_Num>0 && $_Num<160 ){

		return chr($_Num);

	}elseif($_Num<-20319 || $_Num>-10247){

		return '';

	}else{

		foreach($_Data as $k=>$v){ if($v<=$_Num) break; }

		return $k;

	}

}

function _U2_Utf8_Gb($_C){

	$_String = '';

	if($_C < 0x80){

		$_String .= $_C;

	}elseif($_C < 0x800){

		$_String .= chr(0xC0 | $_C>>6);

		$_String .= chr(0x80 | $_C & 0x3F);

	}elseif($_C < 0x10000){

		$_String .= chr(0xE0 | $_C>>12);

		$_String .= chr(0x80 | $_C>>6 & 0x3F);

		$_String .= chr(0x80 | $_C & 0x3F);

	}elseif($_C < 0x200000){

		$_String .= chr(0xF0 | $_C>>18);

		$_String .= chr(0x80 | $_C>>12 & 0x3F);

		$_String .= chr(0x80 | $_C>>6 & 0x3F);

		$_String .= chr(0x80 | $_C & 0x3F);

	}

	return iconv('UTF-8','gbk',$_String);
}
?>